package com.itly.rwzq.utils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created with IntelliJ IDEA.
 * @Author: 罗言
 * @Version: 1.0
 * @Date: 2023-11-12-17:44
 * @Description: 发送请求工具类
 */
@SuppressWarnings("all")
public class SendRequest {
     public static String sendRequest(String urlParam, String requestType) {
         HttpURLConnection con = null;
         BufferedReader buffer = null;
         StringBuffer resultBuffer = null;
         OutputStream out = null;
         try{
             URL url = new URL(urlParam);
             // 获取连接对象
             con = (HttpURLConnection) url.openConnection();
             // 设置请求类型
             con.setRequestMethod(requestType);
             // 设置请求需要返回的数据类型和字符集类型
             con.setRequestProperty("Content-Type", "application/json;charset=utf8");
             con.setRequestProperty("connection", "Keep-Alive");
             // U-A 伪装
             String UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36 Edg/119.0.0.0";
             con.setRequestProperty("User-Agent", UA);
             // 允许写出
             con.setDoInput(true);
             // 允许读入
             con.setDoInput(true);
             // 未知 报错添加的
             con.setDoOutput(true);
             // 不使用缓存
             con.setUseCaches(false);
             // 开始连接
             con.connect();

             // 传递参数 流的方式
//             out = con.getOutputStream();
//             out.write(param.getBytes());
//             out.flush();
             // 得到响应码
             int responseCode = con.getResponseCode();
             // 根据得到的响应码进行判断后后续操作
             if(responseCode == HttpURLConnection.HTTP_OK) {
                // 得到响应流
                 InputStream inputStream = con.getInputStream();
                 // 得响应流转换成字符串
                 resultBuffer = new StringBuffer();
                 String line;
                 buffer = new BufferedReader(new InputStreamReader(inputStream, "utf8"));
                 while ((line = buffer.readLine()) != null) {
                     resultBuffer.append(line);
                 }
                 return  resultBuffer.toString();
             }
         }catch (Exception e) {
            e.printStackTrace();
         }finally {
             // 关闭所有通道
             try {
                if (buffer != null) {
                    buffer.close();
                }
                if (out != null) {
                    out.close();
                }
                if (con != null) {
                    con.disconnect();
                }
             }catch (Exception e2) {
                 e2.printStackTrace();
             }
         }
         return "出错了";
     }
}
